# coding=utf-8
# 审方（逻辑处理）

import json
import time, datetime
import cx_Oracle
import logging
import requests
from bson.objectid import ObjectId
from config.base_config import HOSP_CODE, DEPT_CODE

from modules.schema.utils import getdata
from api.oldaudit.format_xml import PREBASE_XML, PRESCRIPTION_XML,\
    MEDICINESDATA, DIAGNOSEDATA

LOG = logging.getLogger("process")

def xml_opbase(base_data):
    doct_code = getdata(base_data[3])
    doct_name = getdata(base_data[4])
    dept_code = getdata(base_data[5])
    dept_name = getdata(base_data[6])

    base_xml = PREBASE_XML.format(
        hosp_code=HOSP_CODE,
        dept_code=dept_code, dept_name=dept_name,
        doct_code=doct_code, doct_name=doct_name
    )
    return base_xml

def xml_opmedicine(cf_data):    
    medicine_list = ""
    for item in cf_data:
        medicine = MEDICINESDATA.format(
            name=getdata(item[9]),
            his_code=getdata(item[10]),
            insur_code=getdata(item[11]),
            # pyd_code=getdata(item[12]),
            # link_group=getdata(item[13]),
            spec=getdata(item[14]),
            group=getdata(item[15]),
            reason=getdata(item[16]),
            dose_unit='%s' % getdata(item[17]),
            dose=getdata(item[18]),
            ord_qty=int(getdata(item[19])),
            ord_uom='%s' % getdata(item[20]),
            freq=getdata(item[21]),
            administer=getdata(item[22]),
            begin_time='',
            end_time='',
            days=getdata(item[26]),
        )
        medicine_list += medicine
    return medicine_list

def xml_opdetail(base_data, cf_data, jbzd_data, checktype):
    """
    checktype: 0 预审, 1 审方
    """
    cf_first = cf_data[0]
    medicine_list = xml_opmedicine(cf_data)
    diag_list = xml_jbzd(jbzd_data)
    birth = ''
    if isinstance(base_data[9],unicode):
        birth = getdata(base_data[9])
    else:
        birth = getdata(base_data[9]).strftime('%Y-%m-%d')
    xml_data = PRESCRIPTION_XML.format(
        checktype=checktype,
        his_time=getdata(base_data[0]),
        hosp_flag=getdata(base_data[1]),
        treat_type=getdata(base_data[2]),
        treat_code=getdata(base_data[3]),
        bed_no=getdata(base_data[5]),
        area_code=getdata(base_data[6]),
        name='%s' % getdata(base_data[7]),
        # is_infant=getdata(base_data[8]),
        birth=birth,
        # birth=getdata(base_data[9]),
        sex='%s' % getdata(base_data[10]),
        weight=getdata(base_data[11]),
        height=getdata(base_data[12]),
        card_code=getdata(base_data[13]),
        card_type=getdata(base_data[14]),
        id_card=getdata(base_data[13]),
        pregnant_unit='',
        pregnant='',
        allergic_data='',
        diagnose_data=diag_list,

        id=cf_first[0],
        reason='',
        is_new=cf_first[1],
        is_current=cf_first[2],
        doct_code=cf_first[3],
        doct_name='%s' % cf_first[4],
        dept_code=cf_first[5],
        dept_name='%s' % cf_first[6],
        # dept_code=DEPT_CODE,
        # dept_name='',
        pres_type='T',
        pres_time=cf_first[8],
        medicine_list=medicine_list
    )
    return xml_data

def xml_jbzd(jbzd_data):
    diag_list = ''
    for item in jbzd_data:
        diagnose_data = DIAGNOSEDATA.format(
            type = 0,
            name = getdata(item[3]),
            code = getdata(item[2]),
        )
        diag_list += diagnose_data
    return diag_list

# 门诊审方数据处理拼装
def opdata_to_json(base_data, cf_data, jbzd_data, lis_data, pacs_data):
    base_first = base_data[0]
    cf_first = cf_data[0]
    tsrq = 0
    if base_first[19]:
        tsrq = 1

    # 药品列表
    drug_list = []
    for drug_item in cf_data:
        # totalprice = 0
        # if drug_item[18] and drug_item[26]:
        #     totalprice = float(drug_item[18]) * float(drug_item[27])
        drug = {
            "name" : drug_item[9],
            "code" : drug_item[10],
            "insurcode" : drug_item[11],
            "group" : getdata(drug_item[15]),
            "link_group" : getdata(drug_item[13]),
            "spec" : getdata(drug_item[14]),
            "spec_str":getdata(str(drug_item[14])) + getdata(str(drug_item[39])),
            "doseunit" : getdata(drug_item[17]),
            "dose" : getdata(drug_item[18]),
            "order" : getdata(drug_item[19]),
            "orderunit" : getdata(drug_item[20]),
            "freq" : getdata(drug_item[21]),
            "freq_name" : getdata(drug_item[37]),
            "usage" : getdata(drug_item[22]),
            "usage_name" : getdata(drug_item[38]),
            "price" : getdata(drug_item[27]),
            "totalprice" : getdata(drug_item[36]),
            "days" : getdata(drug_item[26])
        }
        drug_list.append(drug)

    # 诊断列表
    diag_list = []
    for diag_item in jbzd_data:
        diag = {
            "type" : 0,
            "code" : getdata(diag_item[2]),
            "name" : getdata(diag_item[3])
        }
        diag_list.append(diag)

    # lis数据列表
    lis_list = []
    # lis_key_list = {}
    # child_list = []
    # for lis_item in lis_data:
    #     lisno = str(lis_item[0])

    #     lisno_list = []
    #     for no in lis_key_list:
    #         lisno_list.append(no[0])

    #     child_dict = {
    #         "name" : lis_item[3],
    #         "code" : lis_item[4],
    #         "value" : getdata(lis_item[5]),
    #         "unit" : getdata(lis_item[6]),
    #         "result" : getdata(lis_item[7]),
    #         "range" : getdata(lis_item[8])
    #     }
    #     child_list.append(child_dict)

    #     if lisno in lisno_list:
    #         lis_key_list[lisno]["items"].append(child_dict)
    #     else:
    #         reporttime_lis = ''
    #         if lis_item[1]:
    #             reporttime_lis = lis_item[1].strftime('%Y-%m-%d %H:%M:%S')
    #         lis_key_list["lisno"] = {
    #             "lisno" : lisno,
    #             "reporttime" : reporttime_lis,
    #             "lisname" : lis_item[2],
    #             "items" : child_list
    #         }
    # lis_list = lis_key_list.values()

    # pacs数据列表
    pacs_list = []
    for pacs_item in pacs_data:
        # reporttime_pacs = ''
        # if pacs_item[1]:
        #     reporttime_pacs = pacs_item[1].strftime('%Y-%m-%d %H:%M:%S')
        pacs = {
            "pacsno" : pacs_item[0],
            "reporttime" : getdata(pacs_item[1]),
            "patientid" : getdata(pacs_item[2]),
            "studyid" : getdata(pacs_item[3]),
            "name" : getdata(pacs_item[4]),
            "value" : getdata(pacs_item[5]),
            "result" : getdata(pacs_item[6])
        }
        pacs_list.append(pacs)


    birth = ''
    if base_first[9]:
        birth = base_first[9].strftime('%Y-%m-%d %H:%M:%S')
    prestime = ''
    if cf_first[8]:
        prestime = cf_first[8].strftime('%Y-%m-%d %H:%M:%S')
    
    json_data = {
        "body":{
            "hospcode" : '11-0001',
            "hospname" : '银川市第一人民医院',
            "deptcode" : cf_first[5],
            "deptname" : cf_first[6],
            "doctcode" : cf_first[3],
            "doctname" : cf_first[4],
            "doctlevel" : '',
            "prestype" : getdata(str(cf_first[34])),
            "treatcode" : getdata(base_first[3]),
            "patientname" : base_first[7],
            "patientsex" : base_first[10],
            "patientid" : cf_first[31],
            "telphone" : '',
            "birth" : birth,
            "height" : getdata(base_first[12]),
            "weight" : getdata(base_first[11]),
            "bodysurface" : '',
            "idcard" : getdata(base_first[13]),
            "cardcode" : getdata(base_first[18]),
            "healthcode" : '',
            "totalprice" : cf_first[36],
            "tsrq" : tsrq,
            "tsrqtype" : base_first[19],
            "ggnbq" : '',
            "sgnbq" : '',
            "gxybs" : '',
            "gxybsLevel" : '',
            "tnbs" : '',
            "tnbstype" : '',
            "xzbs" : '',
            "qttsjb" : '',
            "qttsjbName" : '',
            "prescription" : {
                "id" : cf_first[0],
                "prestime": prestime,
                "items": drug_list         # 药品列表
            },    # 处方字典(含药品列表)
            "allergic" : [],        # 过敏列表
            "diagnose" : diag_list,        # 诊断列表
            "lisdata" : lis_list,         # lis数据列表
            "pacsdata" : pacs_list,        # pacs数据列表
            "operation" : []        # 手术信息列表
        }    
    }

    return json_data